package hu.pixelesztergalyos.continuity;

import hu.pixelesztergalyos.gui.Controller;

import java.awt.event.KeyEvent;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Game {

  public boolean ks[];      // ks: keyboardState
  private Level level;      // level: active loaded level
  private int levelNumber;  // levelNumber: number of the level
  public Controller c;      // c: controller for handling display and model update

	// Constructor
	public Game() {
		ks = new boolean[255];  // Assumes we have no more than 255 keys
	}

	/**
	 * 
	 * @return
	 * @throws IOException 
	 */
	// Updates the game
	public void update(GameState gs) throws IOException {
		if (gs == GameState.PLAYING) {
			// When a level is finished, lets save the current levelnumber into a text file for later use
      if (level.getIsCompleted()){
				try{
				  FileWriter fw = new FileWriter("levelID.txt");                              // Opening file for storing levelnumber
	  			PrintWriter pw = new PrintWriter(fw);                                       // Opening PrinteWriter for output
				
        int newId = level.getId()+1;                                                  // newID: for loading next level
			  	pw.println(newId);                                                          // write to file the ID of the currently accessed level
          level = new Level("continuity_L" + String.format("%03d", newId) + ".xml");  // level: load next level into the level container
          level.setIsCompleted(false);                                                // setisCompleted(false): set completetion test to false
          level.owner = this;                                                         // owner: set owner to game entity for integrity reasons
          level.setViewState(ViewState.LEVEL);                                        // setViewState(ViewState.LEVEL): set view to level overview 
          pw.close();                                                                 // pw.close(): close output handler
				}catch(Exception e){
					System.out.println("Fileba iras sikertelen");
				}
			}
			else {
        // If "SPACE" pressed, change View
				if (ks[' ']) {
					if (level.getViewState() == ViewState.LEVEL) level.setViewState(ViewState.MOSAIC); // if in level view, switch to mosaic view
					else level.setViewState(ViewState.LEVEL);                                          // if in mosaic view, switch to level view
					ks[' '] = false;                                                                   // reset key press stated to "unpressed"
				}
				level.update();                                                                      // update statuses
			}
		}
		c.setModelData(level.getCharacter(1), level.getCharacter(2),
				level.getGate(), level.getKey(), level.getMosaics(),
				level.getCurrentMosaicCoord());
	}

	public void loadLevel(String name) throws IOException // Only needed in the proto													
	{
		level = new Level(name);
		level.owner = this;
		c.setModelData(level.getCharacter(1), level.getCharacter(2),
				level.getGate(), level.getKey(), level.getMosaics(),
				level.getCurrentMosaicCoord());
	}

  // moveCharacter: given character moves in given direction
	public void moveCharacter(int which, Direction dir) throws IOException {
		level.getCharacter(which).move(dir);
	}
  
  // changeView(): switches to other viewState
	public void changeView() throws IOException {
		if (level.getViewState() == ViewState.LEVEL)
			level.setViewState(ViewState.MOSAIC);
		else
			level.setViewState(ViewState.LEVEL);
	}

  // moveMosaic: moves available mosaic in given direction
	public void moveMosaic(Direction dir) throws IOException {
		level.moveMosaic(dir);
	}

  // skipLevel(): skips current level and loads next level
	public void skipLevel() throws IOException {
    int newId = level.getId() + 1;                                             // newId: loads next map id based on current id
    level.setIsCompleted(true);                                                // setIsCompleted(true): sets current maps state to completed
    level = new Level("continuity_L" + String.format("%03d", newId) + ".xml"); // level: loads next level into level entity
    level.owner = this;                                                        // owner: ensures integrity
	}

	// For proto writeout
	public void writeLevel(String filename) {
		level.writeLevel(filename);
	}

	/**
	 * 
	 * @return
	 */
	public int getLevelNumber() {
		return levelNumber;                  // retrieves the currently loaded level's ID
	}

	/**
	 * 
	 * @return
	 */
	public void setLevelNumber() {
     this.levelNumber = levelNumber;     // levelNumber: sets the ID of the current level
	}

	public Level getLevel() {
     return level;                       // retrieves the currently loaded level entity
	}

}
